package cn.itcast.bos.web.action.take_delivery;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 处理kindeditor图片上传 、管理功能
 *
 * @author ChuanJing
 * @date 2018/6/4 14:50
 */
@Controller
public class ImageController {

    /**
     * kindeditor编辑器中上传来的大图片，正文图片；写的很简陋，只实现了简单的上传功能，没有考虑极端情况
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/image_upload", method= RequestMethod.POST)
    @ResponseBody
    public Map upload(MultipartFile imgFile, HttpServletRequest request) throws IOException {
        // 绝对路径
        String savePath = request.getSession().getServletContext().getRealPath("/upload/");
        System.out.println("绝对路径：" + savePath);//最后没有“/”
        // 相对路径
        String saveUrl = request.getContextPath() + "/upload/";
        System.out.println("相对路径：" + saveUrl);//最后有“/”

        // 生成随机图片名
        UUID uuid = UUID.randomUUID();
        //取文件扩展名
        String oriName = imgFile.getOriginalFilename();
        String extName = oriName.substring(oriName.lastIndexOf("."));
        String randomFileName = uuid + extName;

        // 保存图片 (绝对路径)
        File destFile = new File(savePath + "/" + randomFileName);
        // System.out.println("保存图片 (绝对路径)：" + destFile.getAbsolutePath());
        imgFile.transferTo(destFile);

        // 通知浏览器文件上传成功
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("error", 0);
        result.put("url", saveUrl + randomFileName); // 返回相对路径

        return result;
    }

    @RequestMapping("/image_manage")
    @ResponseBody
    public Map manage(HttpServletRequest request) throws IOException {
        // 根目录路径，可以指定绝对路径，比如 d:/xxx/upload/xxx.jpg
        String rootPath = request.getSession().getServletContext().getRealPath("/") + "upload/";
        // 根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
        String rootUrl = request.getContextPath() + "/upload/";

        // 当前上传目录
        File currentPathFile = new File(rootPath);
        // 图片扩展名
        String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
        // 遍历目录取的文件信息
        List<Map<String, Object>> fileList = new ArrayList<Map<String, Object>>();
        if(currentPathFile.listFiles() != null) {
            for (File file : currentPathFile.listFiles()) {
                Hashtable<String, Object> hash = new Hashtable<String, Object>();
                String fileName = file.getName();
                if(file.isDirectory()) {
                    hash.put("is_dir", true);
                    hash.put("has_file", (file.listFiles() != null));
                    hash.put("filesize", 0L);
                    hash.put("is_photo", false);
                    hash.put("filetype", "");
                } else if(file.isFile()){
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    hash.put("is_dir", false);
                    hash.put("has_file", false);
                    hash.put("filesize", file.length());
                    hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));
                    hash.put("filetype", fileExt);
                }
                hash.put("filename", fileName);
                hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
                fileList.add(hash);
            }
        }

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("moveup_dir_path", "");
        result.put("current_dir_path", rootPath);
        result.put("current_url", rootUrl);
        result.put("total_count", fileList.size());
        result.put("file_list", fileList);

        return result;
    }
}
